package spaceshop

import (
	"time"

	"errors"

	"encoding/json"

	"strings"

	"github.com/astaxie/beego/orm"
)

var (
	ErrSupplierFeeItemInvalid          = errors.New("格式错误！")
	ErrSheetNoInvalid                  = errors.New("sheetno invalid!")
	ErrSupplierFeeItemFeeAmountInvalid = errors.New("sheet amount invalid!")
)

const (
	//KMJXCFeeSubNumberName 费用id mysql.kmjxc_sub_number
	KMJXCFeeSubNumberName = "kmjxc_fee_sub_id"
)

func init() {
	orm.RegisterModel(new(SupplierFeeItem))
}

//SupplierFeeItem 费用明细
type SupplierFeeItem struct {
	FeeNo      string    `orm:"pk"`                     //FE费用编码
	FeeAmount  float64   `orm:"digits(10);decimals(2)"` //费用金额
	SupcustNo  string    //所属供应商
	FeeDate    time.Time `orm:"type(date)"`             //费用所属日期
	PaidDate   time.Time `orm:"type(date)"`             //费用扣取日期
	PaidAmount float64   `orm:"digits(10);decimals(2)"` //已扣取金额
	FeeBrief   string    //费用信息
	SignName   string    //申请人
	SheetNo    string    //所属付款单
	Dept       string    `orm:"-"`
}

func GetSupplierFeeItemsBySheetNo(sheetNo string) ([]SupplierFeeItem, error) {
	var sfis []SupplierFeeItem
	if len(sheetNo) == 14 && sheetNo[0:2] == "RP" {
		o := orm.NewOrm()
		qs := o.QueryTable("supplier_fee_item")
		qs = qs.Filter("SheetNo", sheetNo)
		_, err := qs.All(&sfis)
		return sfis, err
	}
	return sfis, ErrSheetNoInvalid

}

func verifySupplierFeeItemData(item SupplierFeeItem) error {
	if !(len(item.SheetNo) == 14 && item.SheetNo[0:2] == "RP") {
		return errors.New("sheetNo invalid!")
	}
	if len(item.SupcustNo) != 6 {
		return errors.New("supcustNo invalid!")
	}
	if !(item.Dept == "03" || item.Dept == "04") {
		return errors.New("dept invalid!")
	}
	return nil
}

func CreateSupplierFeeItemFromJsonBytes(body []byte) (SupplierFeeItem, error) {
	var data map[string]interface{}
	item := SupplierFeeItem{}
	if err := json.Unmarshal(body, &data); err != nil {
		panic(err)
	}
	for i, v := range data {
		switch i {
		case "FeeDate":
			{
				if d, ok := v.(time.Time); ok {
					item.FeeDate = d
				} else if d, err := time.Parse("2006-01-02", v.(string)); err == nil {
					item.FeeDate = d
				} else {
					return item, err
				}
			}
		case "FeeAmount":
			{
				if d, ok := v.(float64); ok {
					item.FeeAmount = d
				} else {
					return item, ErrSupplierFeeItemFeeAmountInvalid
				}
			}
		case "FeeBrief":
			{
				item.FeeBrief = v.(string)
			}
		case "SheetNo":
			{
				item.SheetNo = v.(string)
			}
		case "SupcustNo":
			{
				item.SupcustNo = strings.Replace(v.(string), " ", "", -1)
			}
		case "Dept":
			{
				item.Dept = v.(string)
			}
		case "SignName":
			{
				item.SignName = v.(string)
			}
		case "PaidAmount":
			{
				//todo
			}
		}
	}
	return item, nil
}

//AddFeeOnRpTRecpayRecordInfo 新增费用项目
func AddFeeOnRpTRecpayRecordInfo(item SupplierFeeItem) (string, error) {
	o := orm.NewOrm()
	//verify data
	if err := verifySupplierFeeItemData(item); err != nil {
		return "", err
	}
	item.FeeNo = NewKmjxcSubNumberManager(KMJXCFeeSubNumberName, func() string {
		return "FE?" + time.Now().Format("060102")
	}).GetSubNo(item.Dept)

	_, err := o.Insert(&item)
	return item.FeeNo, err
}

//UpdateSupplierFeeItemByFeeNo 更新费用
func UpdateSupplierFeeItemByFeeNo(feeNo string, item SupplierFeeItem) error {
	si := SupplierFeeItem{FeeNo: feeNo}
	o := orm.NewOrm()
	err := o.Read(&si)
	if err != nil {
		return err
	}
	si.FeeDate = item.FeeDate
	si.FeeBrief = item.FeeBrief
	si.FeeAmount = item.FeeAmount
	si.SignName = item.SignName
	si.Dept = si.FeeNo[2:4]
	//todo
	//item.PaidAmount = item.FeeAmount
	//verify
	err = verifySupplierFeeItemData(si)
	if err != nil {
		return err
	}
	_, err = o.Update(&si, "fee_date", "fee_brief", "fee_amount", "sign_name")
	return err
}

//UpdateSupplierFeeItemByFeeNo 删除费用
func DeleteSupplierFeeItemByFeeNo(feeNo string) error {
	item := SupplierFeeItem{FeeNo: feeNo}
	_, err := orm.NewOrm().Delete(&item)
	return err
}
